package cn.btks.resultintegration.rule.service.impl;

import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.poi.PoitlUtil;
import cn.btks.resultintegration.rule.dto.export.ProjectExport;
import cn.btks.resultintegration.rule.service.ExportService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lijun
 * @Date 2021/3/28 11:43
 */
@Service
public class ExportServiceImpl implements ExportService {

    @Override
    public ResultState export(ProjectExport projectExport, HttpServletRequest request) throws IOException {
        //导出文件所在文件夹路径
        String srcFilePathDir = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_EXPORT_FILE;
        //生成文件路径
        String srcFinalPath = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_EXPORT_FILE + "研判报告" + ".docx";
        //返回路径
        String srcFinalPathResult = Constants.ACHIEVEMENTS_EXPORT_FILE + "研判报告" + ".docx";
        //模板文件
        String srcTemplateFile = "/res/achievements/export/template/" + "RuleTemplate.docx";
        String srcTemplateFile2 = "C:\\RuleTemplate.docx";
        String srcTemplateFile1 = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_EXPORT_FILE + "RuleTemplate.docx";
        System.out.println(srcFinalPath);
        File dir1 = new File(srcFilePathDir);
        if (!dir1.exists()) {
            dir1.mkdirs();
        }
        File file1 = new File(srcFinalPath);
        if(file1.exists()){
            file1.delete();
        }
        Map<String,Object> contentMap = new HashMap<>();
        contentMap.put("dto",projectExport);
        //Excel工具项
        InputStream inputStream = this.getClass().getResourceAsStream(srcTemplateFile);
        PoitlUtil.GenerateTemplate1(inputStream,srcFinalPath,contentMap);

        //Tip：判定文件是否生成成功
        File fileFinal = new File(srcFinalPath);
        if(!fileFinal.exists()){
            return null;
        }
        return StringUtils.isNotEmpty(srcFinalPathResult) ?
                new ResultState(StateInfo.DOWNLOAD_OK.getCode(), StateInfo.DOWNLOAD_OK.getMsg(), srcFinalPathResult) :
                new ResultState(StateInfo.DOWNLOAD_ERROR.getCode(), StateInfo.DOWNLOAD_ERROR.getMsg());
    }
}
